package com.bestcem.xm.ticket.task;

import cn.hutool.core.collection.CollUtil;
import com.bestcem.xm.ticket.entity.mongo.Ticket;
import com.bestcem.xm.ticket.entity.mongo.TicketNotifyConfig;
import com.bestcem.xm.ticket.enums.FollowerFilterEnum;
import com.bestcem.xm.ticket.enums.UserStatusEnum;
import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.user.GroupDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.RoleDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.UserDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.UserGroupDTO;
import com.bestcem.xm.ticket.service.manager.role.BaseTicketRole;
import com.bestcem.xm.ticket.service.manager.role.TicketAuditor;
import com.bestcem.xm.ticket.service.manager.role.TicketFollower;
import com.bestcem.xm.ticket.util.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import java.util.*;

/**
 * 异步任务
 *
 * @author gy.liu
 * @version 1.0
 * @date 2021/8/30 16:51
 **/
@Component
public class TicketTask {

    public static String TICKETS_STATISTICS_EMAIL_TEMPLATE = "<!DOCTYPE html>\n" +
            "<head>\n" +
            "    <style>\n" +
            "        .square {{\n" +
            "            width: 116px;\n" +
            "            height: 124px;\n" +
            "            border-radius: 4px;\n" +
            "            text-align: center;\n" +
            "            border: 1px solid #e1e1e1;\n" +
            "            margin: 0 16px 0 0;\n" +
            "            display: inline-block\n" +
            "        }}\n" +
            "        .number {{\n" +
            "            font-size: 24px;\n" +
            "            font-weight: 700;\n" +
            "            color: #333;\n" +
            "            padding-top: 16px;\n" +
            "            margin: 16px 0 0 0\n" +
            "        }}\n" +
            "        .text {{\n" +
            "            margin-top: 0\n" +
            "        }}\n" +
            "    </style>\n" +
            "</head>\n" +
            "<body>\n" +
            "    <p>截止 {today}，工单统计如下：</p>\n" +
            "    <p><b>截至 {today}，需要您处理的工单：</b></p>\n" +
            "    <div class=\"square-row\">\n" +
            "        <div class=\"square\">\n" +
            "            <p class=\"number\">{followingCnt}</p>\n" +
            "            <p class=\"text\">跟进中</p>\n" +
            "        </div>\n" +
            "        <div class=\"square\">\n" +
            "            <p class=\"number\">{auditingCnt}</p>\n" +
            "            <p class=\"text\">审核中</p>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "    <p><b>截至{today}，您查看权限内的工单：</b></p>\n" +
            "    <div class=\"square-row\">\n" +
            "        <div class=\"square\">\n" +
            "            <p class=\"number\">{totalCnt}</p>\n" +
            "            <p class=\"text\">新增工单</p>\n" +
            "        </div>\n" +
            "        <div class=\"square\">\n" +
            "            <p class=\"number\">{auditingCnt}</p>\n" +
            "            <p class=\"text\">完成跟进</p>\n" +
            "        </div>\n" +
            "        <div class=\"square\">\n" +
            "            <p class=\"number\">{manualClosedCnt}</p>\n" +
            "            <p class=\"text\">手动关闭</p>\n" +
            "        </div>\n" +
            "        <div class=\"square\">\n" +
            "            <p class=\"number\">{systemClosedCnt}</p>\n" +
            "            <p class=\"text\">自动关闭</p>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "</body>\n" +
            "</html>";

    @Resource
    private TicketUserGrpcService ticketUserGrpcService;

    @Resource
    private TicketBaseUserGrpcService ticketBaseUserGrpcService;

    @Resource
    private CommonUtils commonUtils;

    /**
     * 获取抄送用户
     * 5828
     *
     * @param ticket
     * @param roleRegion
     * @return
     * @author liheng
     * @date 2021/9/2 14:11
     */
    public List<UserDTO> getHasPermUserByCc(Ticket ticket, TicketNotifyConfig.RoleRegion roleRegion) {
        Integer filter = Optional.ofNullable(roleRegion).map(TicketNotifyConfig.RoleRegion::getCcFilter).orElse(FollowerFilterEnum.REGION.getIndex());
        List<UserDTO> userDTOS = new ArrayList<>(10);
        if (FollowerFilterEnum.REGION.getIndex().equals(filter)) {
            List<UserDTO> users = ticketUserGrpcService.listUsersByRole(roleRegion.getRoleId(), ticket.getRegion(), roleRegion.getRegion());
            if (CollUtil.isNotEmpty(users)) {
                userDTOS.addAll(users);
            }
        } else if (Objects.nonNull(roleRegion.getCcId())) {
            List<UserDTO> users = this.getUserIsHeadquarters(Arrays.asList(roleRegion.getCcId()));
            if (CollUtil.isNotEmpty(users)) {
                userDTOS.addAll(users);
            }
        }
        return userDTOS;

    }

    /**
     * 获取有权限跟进工单的用户(上面的方法重载，适配不同的入参)
     *
     * @param ticket
     * @param role
     * @return
     */
    public List<UserDTO> getHasPermUserByFollower(Ticket ticket, BaseTicketRole role) {
        if (Objects.isNull(role)) {
            return Collections.emptyList();
        }
        if (role instanceof TicketAuditor) {
            return Collections.emptyList();
        }
        if (role instanceof TicketFollower) {
            TicketFollower follower = (TicketFollower) role;
            if (FollowerFilterEnum.REGION.equals(follower.getFollowerFilter())) {
                List<UserDTO> userDTOS = ticketUserGrpcService.listUsersByRole(follower.getRoleId(), ticket.getRegion(), role.getRegion());
                return Optional.ofNullable(userDTOS).orElse(new ArrayList<>());
            }
            if (FollowerFilterEnum.USER.equals(follower.getFollowerFilter()) && ObjectId.isValid(follower.getFollowerId())) {
                List<UserDTO> userDTOS = this.getUserIsHeadquarters(Arrays.asList(follower.getFollowerId()));
                return Optional.ofNullable(userDTOS).orElse(new ArrayList<>());
            }
        }
        return new ArrayList<>();
    }

    /**
     * 判断当前用户是否属于总部层级，并且账号是否属于启用状态
     *
     * @param userIds
     * @return void
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/30
     */
    @Nonnull
    public List<UserDTO> getUserIsHeadquarters(@Nonnull List<String> userIds) {
        List<UserDTO> result = new ArrayList<>();
        List<String> headquartersIds = new ArrayList<>();
        if (CollectionUtils.isEmpty(userIds)) {
            return result;
        }

        String superRoleId = "";
        for (String userId : userIds) {
            // 当前用户
            UserDTO userDTO = ticketBaseUserGrpcService.getUser(userId);
            if (Objects.isNull(userDTO)) {
                continue;
            }
            // 用户所有的角色
            List<String> roleIds = commonUtils.getUserAllRoleId(userId);

            if (ObjectUtils.isEmpty(superRoleId)) {
                // 系统管理员
                List<RoleDTO> roleDTOS = ticketBaseUserGrpcService.listRoleByOrgIdAndRoleName(userDTO.getOrgId(), "系统管理员");
                if (Objects.nonNull(roleDTOS)) {
                    superRoleId = roleDTOS.get(0).getId();
                }
            }

            // 判断用户状态
            if (userDTO.getStatus() != UserStatusEnum.ACTIVATED.getIndex()) {
                continue;
            }

            // 如果是超级管理员
            if (StringUtils.isNotEmpty(superRoleId) && roleIds.contains(superRoleId)) {
                result.add(userDTO);
                continue;
            }

            // 判断当前用户层级
            // 获取总部层级
            List<GroupDTO> groupDTOS = ticketUserGrpcService.listHeadQuarterGroupsByOrgId(userDTO.getOrgId());
            if (!CollectionUtils.isEmpty(groupDTOS)) {
                for (GroupDTO groupDTO : groupDTOS) {
                    headquartersIds.add(groupDTO.getId());
                }
            }
            // 获取总部层级的所有用户id
            List<String> headquartersUserIds = new ArrayList<>();
            for (String headQuarter : headquartersIds) {
                List<UserGroupDTO> userGroupDTOS = ticketBaseUserGrpcService.listUserGroupByGroupId(headQuarter);
                if (!CollectionUtils.isEmpty(userGroupDTOS)) {
                    for (UserGroupDTO userGroup : userGroupDTOS) {
                        headquartersUserIds.add(userGroup.getUserId());
                    }
                }
            }
            // 如果用户在总部层级 ， 添加到返回结果
            if (headquartersUserIds.contains(userDTO.getId())) {
                result.add(userDTO);
            }
        }
        return result;
    }

}
